from flask import Flask, render_template,jsonify
import config
from models import db

app = Flask(__name__)
# 添加配置
app.config.from_object(config)
# 数据库绑定app
db.init_app(app)

def do_sql(select_sql):
    data = db.session.execute(select_sql).fetchall()
    dic = {}
    for i in data:
        dic[i[0]] = i[1]
    return jsonify(dic)

@app.route("/")
def index():
    return render_template("index.html")

# 获得租房类型饼图数据
@app.route("/get_pie_data")
def get_pie_data():
    select_sql = "select type, count(*) from home group by type"
    return do_sql(select_sql)

# 获得租房类型条形图数据
@app.route("/get_type_bar_data")
def get_type_bar_data():
    select_sql = "SELECT type, round(avg(room_price),2) FROM `home` group by type"
    return do_sql(select_sql)

# 获得合租房类型折线图数据
@app.route("/get_hz_line_data")
def get_hz_line_data():
    select_sql = "select room_type, round(avg(room_price), 2) from home where type='合租' group by room_type"
    return do_sql(select_sql)

# 获得整租房类型折线图数据
@app.route("/get_zz_line_data")
def get_zz_line_data():
    select_sql = "select room_type, round(avg(room_price), 2) from home where type='整租' group by room_type"
    return do_sql(select_sql)

# 获得深圳各区租房条形图数据
@app.route("/get_type_qu_bar_data")
def get_type_qu_bar_data():
    select_sql = "SELECT room_addr_qu, round(avg(room_price),2) as avg_price FROM `home` group by room_addr_qu"
    return do_sql(select_sql)

# 获得深圳各区租房条形图数据
@app.route("/get_fb_pie_data")
def get_fb_pie_data():
    select_sql = "SELECT room_addr_qu, count(room_price) FROM `home` group by room_addr_qu"
    return do_sql(select_sql)

if __name__ == "__main__":
    app.run()